import matplotlib.pyplot as plt
import wave
import numpy as np
import datetime

def save_audio(filename, frames):
    with wave.open(filename, "wb") as wf:
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(rate)
        wf.writeframes(b"".join(frames))

def calculate_threshold(audio_data):
    max_amplitude = np.max(audio_data)
    hit_threshold = int(0.5 * max_amplitude)

    print(f"threshold: {hit_threshold}")
    return hit_threshold

def count_hits(audio_data, threshold):
    hit_count = 0
    skip_count = 0

    for i, sample in enumerate(audio_data):
        if skip_count > 0:
            skip_count -= 1
            continue

        if sample > threshold:
            print(f"HIT: {i}: {sample}")
            hit_count += 1
            skip_count = 199 # int(rate / chunk_size * cooldown_time)

    return hit_count

def plot_waveform(audio_data, duration=3):
    plt.figure(figsize=(14, 5))
    plt.plot(audio_data)
    plt.xlabel("Sample")
    plt.ylabel("Amplitude")
    plt.title("Waveform")
    plt.grid(True)

    # 定时器，设定时间后自动关闭窗口
    timer = plt.gcf().canvas.new_timer(interval=duration * 1000)
    timer.add_callback(plt.close)
    timer.start()

    plt.show()  # 添加这一行来显示图形窗口

def get_user_choice():
    valid_choices = ["剪刀", "石头", "布"]
    while True:
        user_choice = input("请输入您的选择（剪刀、石头或布）：")
        if user_choice in valid_choices:
            return user_choice
        else:
            print("无效的选择，请重新输入。")

rate = 44100  # 采样率
chunk_size = 1024  # 每次读取音频的块大小
record_seconds = 3  # 录制音频的秒数
threshold_multiplier = 1.2  # 阈值乘数，用于计算 HIT 的阈值
buffer_size = 1024  # 缓冲区大小
